package project.mafia.network;




import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ConnectionForServer extends Thread {
	private Server server;
	private Socket socket;
	private ObjectInputStream oistream;
	private ObjectOutputStream oostream;
	private boolean running;
	public ConnectionForServer(Server sv, Socket s, ObjectInputStream o) throws IOException {
		server = sv;
		socket = s;
		oistream = o;
		oostream = new ObjectOutputStream(socket.getOutputStream());
	}
	public boolean isRunning(){
		return running;
	}
	public void run(){
		running = true;
		Packet receive;
		while(running){
			try {
				receive = (Packet)oistream.readObject();
				switch(receive.getType()){
				case 0: // connect
				break;
				case 1: // disconnect
					close();
					stopConnectionThread();
					// make disconnect message
					break;
				case 2: // user data
					String[] userData = receive.getData();
					for(int i = 0; i < userData.length; i++){
						switch(i){
						case 0:	
							System.out.println("Nick Name : " + userData[i]);
							break;
						case 1:	
							System.out.println("Job : " + userData[i]);
							break;
						case 2:	
							System.out.println("Condition : " + userData[i]);
							break;
						}
					}
					server.addPacket(receive);
					break;
				case 3:
					server.addPacket(receive);
					break;
				}

			} catch (ClassNotFoundException | IOException e) {
				e.printStackTrace();
			}
		}
	}
	public void sendPacket(Packet p) throws IOException{
		oostream.writeObject(p);
		oostream.flush();
	}
	/**
	 * Close socket stuff
	 * @throws IOException
	 */
	public void close() throws IOException{
		oistream.close();
		oostream.close();
		socket.close();
	}
	public void stopConnectionThread(){
		running = false;
	}
}
